package com.imooc.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.common.ResultInfoUtil;
import com.imooc.mall.dao.ProductMapper;
import com.imooc.mall.dto.ProductDto;
import com.imooc.mall.pojo.Product;
import com.imooc.mall.service.ICategoryService;
import com.imooc.mall.service.IProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@SuppressWarnings("all")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public ResultInfo<PageInfo> list(Integer categorId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIdSet=new HashSet<>();
        if (null!=categorId) {
            categoryService.findSubCategoryId(categorId,categoryIdSet);//所有子类
            //上面查出了所有子类的，现在也要把自身id加进去
            categoryIdSet.add(categorId);
        }
        //根据这个idSet,查所有商品
        PageHelper.startPage(pageNum,pageSize);
        List<Product> productList=productMapper.findByCategoryIdSet(categoryIdSet);
        List<ProductDto> collect = productList.stream().map(x -> productToProductDto(x)).collect(Collectors.toList());
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(collect);
        return ResultInfoUtil.success(pageInfo);
    }

    @Override
    public Product findById(Integer productId) {
        return productMapper.selectByPrimaryKey(productId);
    }

    private ProductDto productToProductDto(Product product) {
        ProductDto productDto=new ProductDto();
        BeanUtils.copyProperties(product,productDto);
        return productDto;
    }
}
